﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using MessageService.DataAccessService;
using MessageService.UserService;
using MessageServiceNamespace;
using Message = MessageService.DataAccessService.Message;
using User = MessageService.DataAccessService.User;


namespace MessageService
{
    class MessageServiceFoo : IMessageService
    {
        private static readonly Uri DataAccessAddress = new Uri("http://localhost:3151/DataAccess.svc");
        private SiteXtenderEntities dataAccessService = new SiteXtenderEntities(DataAccessAddress);

        public void SendMessage(Message message)
        {
            MessageServiceNamespace.Program.logService.Trace(@"""Send Message"" invoked");

            dataAccessService.AddToMessageSet(message);
            try
            {
                dataAccessService.SaveChanges();
            }
            catch (Exception ex)
            {
                Program.logService.Error("DataAccessService not working");
                throw new FaultException("DataAccessService not working");
            }
        }

        public IEnumerable<Message> GetLastMessages(Uri address, int count)
        {
            MessageServiceNamespace.Program.logService.Trace(@"""Get Last messages"" invoked");
            return dataAccessService.MessageSet.OrderByDescending(m => m.DateTime).
                    Where(m => m.Uri == address.ToString()).
                    Take(count);
        }

        public Message GetLastMessage(Uri address)
        {
            MessageServiceNamespace.Program.logService.Trace(@"""Get Last message"" invoked");
            Message message = dataAccessService.MessageSet.Where(m => m.Uri == address.ToString()).OrderByDescending(m=> m.DateTime).First();
            var receivedUser = new UserServiceClient().GetByMessageId(message.Id);
            if(receivedUser!=null)
                message.User = (User) new UserServiceClient().GetByMessageId(message.Id);
            return message;
        }
    }
}
